<?php
/* © 2020-2025 ALYR.NET */
/**
 * 图片内容审核和LOGO识别API
 * 使用百度云AI接口
 * 支持图片内容审核和LOGO识别功能
 */

// 引入配置文件
require_once '../config.php';

// 检查用户登录状态
require_once '../session_check.php';
smart_auth_check();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'status' => 'error',
        'message' => '只允许POST请求'
    ]);
    exit;
}

// 检查文件上传
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        'status' => 'error',
        'message' => '请上传图片文件'
    ]);
    exit;
}

$file = $_FILES['image'];
$analysisType = $_POST['analysis_type'] ?? 'content';

// 验证文件类型
if (!in_array($file['type'], ALLOWED_TYPES)) {
    echo json_encode([
        'status' => 'error',
        'message' => '不支持的文件类型，请上传JPG、PNG、BMP格式的图片'
    ]);
    exit;
}

// 额外验证文件扩展名
$fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowedExtensions = ['jpg', 'jpeg', 'png', 'bmp'];
if (!in_array($fileExtension, $allowedExtensions)) {
    echo json_encode([
        'status' => 'error',
        'message' => '文件扩展名不支持，请确保文件为JPG、PNG或BMP格式'
    ]);
    exit;
}

// 验证文件大小
if ($file['size'] > MAX_FILE_SIZE) {
    echo json_encode([
        'status' => 'error',
        'message' => '文件大小不能超过' . (MAX_FILE_SIZE / 1024 / 1024) . 'MB'
    ]);
    exit;
}

// 根据分析类型调用不同的API
try {
    if ($analysisType === 'logo') {
        $result = analyzeLogoWithBaidu($file);
    } else {
        $result = analyzeContentWithBaidu($file);
    }
    
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => '分析失败: ' . $e->getMessage()
    ]);
}

/**
 * 使用百度云API进行内容审核
 */
function analyzeContentWithBaidu($file) {
    // 百度云图片审核API配置
    $apiKey = BAIDU_CONTENT_API_KEY;
    $secretKey = BAIDU_CONTENT_SECRET_KEY;
    
    // 检查API密钥是否为空或默认值
    if (empty($apiKey) || empty($secretKey) || $apiKey === 'YOUR_BAIDU_API_KEY' || $secretKey === 'YOUR_BAIDU_SECRET_KEY') {
        return simulateBaiduContentResponse($file['name']);
    }
    
    // 获取访问令牌
    $accessToken = getBaiduAccessToken($apiKey, $secretKey);
    if (!$accessToken) {
        throw new Exception('获取百度云访问令牌失败');
    }
    
    // 构建API URL
    $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $accessToken;
    
    // 读取并编码图片
    $imageData = file_get_contents($file['tmp_name']);
    $imageBase64 = base64_encode($imageData);
    
    // 检查图片大小
    if (strlen($imageBase64) > 4 * 1024 * 1024) {
        throw new Exception('图片编码后大小超过4MB限制');
    }
    
    // 构建请求体
    $postData = [
        'image' => $imageBase64
    ];
    
    // 构建请求头
    $headers = [
        'Content-Type: application/x-www-form-urlencoded'
    ];
    
    // 发送请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    // 检查cURL错误
    if ($error) {
        throw new Exception('网络请求失败: ' . $error);
    }
    
    // 检查HTTP状态码
    if ($httpCode !== 200) {
        throw new Exception('API请求失败，HTTP状态码: ' . $httpCode);
    }
    
    // 解析响应
    $result = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('响应解析失败: ' . json_last_error_msg());
    }
    
    // 检查API错误
    if (isset($result['error_code'])) {
        throw new Exception('百度云API错误: ' . $result['error_msg']);
    }
    
    return convertBaiduContentResponse($result);
}

/**
 * 使用百度云API进行LOGO识别
 */
function analyzeLogoWithBaidu($file) {
    // 百度云LOGO识别API配置
    $apiKey = BAIDU_LOGO_API_KEY;
    $secretKey = BAIDU_LOGO_SECRET_KEY;
    
    // 检查API密钥是否为空
    if (empty($apiKey) || empty($secretKey)) {
        throw new Exception('百度云LOGO识别API密钥未配置');
    }
    
    // 获取访问令牌
    $accessToken = getBaiduAccessToken($apiKey, $secretKey);
    if (!$accessToken) {
        throw new Exception('获取百度云访问令牌失败');
    }
    
    // 构建API URL
    $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/logo?access_token=' . $accessToken;
    
    // 读取并编码图片
    $imageData = file_get_contents($file['tmp_name']);
    $imageBase64 = base64_encode($imageData);
    
    // 检查图片大小
    if (strlen($imageBase64) > 4 * 1024 * 1024) {
        throw new Exception('图片编码后大小超过4MB限制');
    }
    
    // 构建请求体
    $postData = [
        'image' => $imageBase64,
        'custom_lib' => 'false',
        'baike_num' => 5
    ];
    
    // 构建请求头
    $headers = [
        'Content-Type: application/x-www-form-urlencoded'
    ];
    
    // 发送请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    // 检查cURL错误
    if ($error) {
        throw new Exception('网络请求失败: ' . $error);
    }
    
    // 检查HTTP状态码
    if ($httpCode !== 200) {
        throw new Exception('API请求失败，HTTP状态码: ' . $httpCode);
    }
    
    // 解析响应
    $result = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('响应解析失败: ' . json_last_error_msg());
    }
    
    // 检查API错误
    if (isset($result['error_code'])) {
        $errorMsg = '百度云API错误 [' . $result['error_code'] . ']: ' . ($result['error_msg'] ?? '未知错误');
        error_log('LOGO识别API错误: ' . $errorMsg . ' | 完整响应: ' . $response);
        throw new Exception($errorMsg);
    }

    // 记录成功的API响应用于调试
    error_log('LOGO识别API成功响应: ' . $response);
    
    return convertBaiduLogoResponse($result);
}

/**
 * 通用POST请求函数（按照百度云官方示例）
 */
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    $data = curl_exec($curl);//运行curl
    curl_close($curl);
    
    return $data;
}

/**
 * 获取百度云访问令牌（按照百度云官方示例）
 */
function getBaiduAccessToken($apiKey, $secretKey) {
    $url = 'https://aip.baidubce.com/oauth/2.0/token';
    $post_data['grant_type'] = 'client_credentials';
    $post_data['client_id'] = $apiKey;
    $post_data['client_secret'] = $secretKey;
    $o = "";
    foreach ( $post_data as $k => $v ) {
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);
    
    $res = request_post($url, $post_data);
    
    if (!$res) {
        throw new Exception('获取访问令牌网络错误');
    }
    
    $result = json_decode($res, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('访问令牌响应解析失败: ' . json_last_error_msg());
    }
    
    if (isset($result['error'])) {
        throw new Exception('获取访问令牌API错误: ' . $result['error_description']);
    }
    
    return $result['access_token'] ?? null;
}

/**
 * 转换百度云内容审核响应
 */
function convertBaiduContentResponse($response) {
    $conclusion = $response['conclusion'] ?? '';
    $conclusionType = $response['conclusionType'] ?? 1;
    
    // 根据conclusionType确定状态
    switch ($conclusionType) {
        case 1:
            $status = 'safe';
            $message = '可以接单正常使用！';
            break;
        case 2:
            $status = 'unsafe';
            $message = '检测到违规内容';
            break;
        case 3:
            $status = 'warning';
            $message = '内容需要人工审核';
            break;
        case 4:
            $status = 'warning';
            $message = '审核失败';
            break;
        default:
            $status = 'warning';
            $message = '未知状态';
    }
    
    // 提取详细信息
    $details = [];
    if (isset($response['data']) && is_array($response['data'])) {
        foreach ($response['data'] as $item) {
            if (isset($item['msg'])) {
                $details[] = $item['msg'];
            }
        }
    }
    
    // 如果是安全状态且没有详细信息，添加默认提示
    if ($conclusionType == 1 && empty($details)) {
        $details = ['仅代表当前分析的图片没有违规！'];
    }
    
    return [
        'status' => $status,
        'message' => $message,
        'details' => $details,
        'confidence' => $response['confidence'] ?? 0,
        'api_provider' => 'baidu_content',
        'request_id' => $response['log_id'] ?? uniqid(),
        'raw_response' => $response
    ];
}

/**
 * 转换百度云LOGO识别响应
 */
function convertBaiduLogoResponse($response) {
    $result = $response['result'] ?? [];
    
    // 记录原始结果用于调试
    error_log('LOGO识别结果解析: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
    
    if (empty($result)) {
        error_log('LOGO识别: 未检测到任何LOGO');
        return [
            'status' => 'no_logo',
            'message' => '未检测到LOGO',
            'logoInfo' => null,
            'api_provider' => 'baidu_logo',
            'request_id' => $response['log_id'] ?? uniqid()
        ];
    }
    
    // 获取置信度最高的结果
    $topResult = $result[0];
    $confidence = $topResult['probability'] ?? 0;
    $brand = $topResult['name'] ?? '未知品牌';
    
    // 记录识别结果
    error_log('LOGO识别详情: 品牌=' . $brand . ', 置信度=' . $confidence);
    
    // 根据置信度确定状态
    $status = $confidence > 0.5 ? 'logo_detected' : 'low_confidence';
    $message = $confidence > 0.5 ? '检测到LOGO' : '置信度较低';
    
    return [
        'status' => $status,
        'message' => $message,
        'logoInfo' => [
            'brand' => $brand,
            'confidence' => $confidence,
            'location' => $topResult['location'] ?? null
        ],
        'api_provider' => 'baidu_logo',
        'request_id' => $response['log_id'] ?? uniqid(),
        'raw_response' => $response
    ];
}

/**
 * 模拟百度云内容审核响应（用于测试）
 */
function simulateBaiduContentResponse($filename) {
    $filename = strtolower($filename);
    
    // 根据文件名关键词模拟不同结果
    if (strpos($filename, 'porn') !== false || strpos($filename, 'sexy') !== false) {
        $status = 'unsafe';
        $message = '检测到色情内容';
        $details = ['图片包含色情内容'];
        $conclusionType = 2;
    } elseif (strpos($filename, 'violence') !== false || strpos($filename, 'blood') !== false) {
        $status = 'unsafe';
        $message = '检测到暴力内容';
        $details = ['图片包含暴力内容'];
        $conclusionType = 2;
    } elseif (strpos($filename, 'ad') !== false || strpos($filename, 'spam') !== false) {
        $status = 'warning';
        $message = '疑似广告内容';
        $details = ['图片可能包含广告信息'];
        $conclusionType = 3;
    } else {
        $status = 'safe';
        $message = '可以接单正常绣印！';
        $details = ['仅代表当前分析的图片没有违规！'];
        $conclusionType = 1;
    }
    
    return [
        'status' => $status,
        'message' => $message,
        'details' => $details,
        'confidence' => rand(70, 95) / 100,
        'api_provider' => 'baidu_content_simulation',
        'request_id' => 'sim_' . uniqid(),
        'conclusionType' => $conclusionType
    ];
}

/**
 * 模拟百度云LOGO识别响应（用于测试）
 */
function simulateBaiduLogoResponse($filename) {
    $brands = [
        'Apple', 'Nike', 'Coca-Cola', 'McDonald\'s', 'Google',
        'Microsoft', 'Samsung', 'Toyota', 'Mercedes-Benz', 'BMW',
        '苹果', '耐克', '可口可乐', '麦当劳', '谷歌',
        '华为', '小米', '阿里巴巴', '腾讯', '百度',
        '京东', '美团', '滴滴', '字节跳动', '拼多多'
    ];
    
    $filename = strtolower($filename);
    
    // 根据文件名检测品牌
    $detectedBrand = null;
    $confidence = 0;
    
    foreach ($brands as $brand) {
        if (strpos($filename, strtolower($brand)) !== false) {
            $detectedBrand = $brand;
            $confidence = rand(60, 95) / 100;
            break;
        }
    }
    
    // 如果没有检测到特定品牌，随机选择一个
    if (!$detectedBrand && rand(1, 3) === 1) {
        $detectedBrand = $brands[array_rand($brands)];
        $confidence = rand(30, 70) / 100;
    }
    
    if ($detectedBrand) {
        $status = $confidence > 0.5 ? 'logo_detected' : 'low_confidence';
        $message = $confidence > 0.5 ? '检测到LOGO' : '置信度较低';
        
        return [
            'status' => $status,
            'message' => $message,
            'logoInfo' => [
                'brand' => $detectedBrand,
                'confidence' => $confidence,
                'location' => [
                    'left' => rand(10, 50),
                    'top' => rand(10, 50),
                    'width' => rand(100, 200),
                    'height' => rand(50, 100)
                ]
            ],
            'api_provider' => 'baidu_logo_simulation',
            'request_id' => 'sim_' . uniqid()
        ];
    } else {
        return [
            'status' => 'no_logo',
            'message' => '未检测到LOGO',
            'logoInfo' => null,
            'api_provider' => 'baidu_logo_simulation',
            'request_id' => 'sim_' . uniqid()
        ];
    }
}
?>